//
//  taskListAdmin.m
//  SQLiteTesting
//
//  Created by kitinat on 1/28/13.
//  Copyright (c) 2013 EGA. All rights reserved.
//

#import "taskListAdmin.h"

#import "ARC_DB.h"

#import "taskListDetailAdmin.h"

#import <QuartzCore/QuartzCore.h>

#import "SVPullToRefresh.h"

#import "EGAEmployeeInfo.h"

#import "EGAAppDelegate.h"

#import "EGAUtility.h"








@interface taskListAdmin ()

@end

@implementation taskListAdmin



//////////////new
@synthesize arrListNewBook;
@synthesize filteredArrListNewBook;
@synthesize searchBar;
@synthesize isFiltered;
/////////////new



@synthesize tblTaskList;

@synthesize type;

@synthesize lbTitle;

NSArray * arrTask;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}











- (void)viewDidLoad
{
    [super viewDidLoad];
    
    
    /////new
    //add searchbar delegate
    searchBar.delegate = (id)self;
    /////new
    
    [self dismissKeyboard];
        
    [self setTitleWithType];
    
    [self addPullToRefreshToTable];
    
    
    ARC_DB * DB = [[ARC_DB alloc]init];
    
    if ([DB isHasAllTaskInDB] && ![DB internetConnected])
    {
        [self alertNotConnect];
        [self queryAndSetArr];
        [tblTaskList reloadData];
        
        
    }
    else
    {
        
        [self refresh];
    }
    
    //set infinitescrolling for type 3
    if ([type isEqualToString:@"3"])
    {
        [self setInfiniteScrollingForType3TaskCompleted];
    }
}




#pragma dismisskeyboard
- (void)dismissKeyboard {
    [self globalResignFirstResponder];
}
- (void) globalResignFirstResponder {
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    for (UIView * view in [window subviews]){
        [self globalResignFirstResponderRec:view];
    }
}
- (void) globalResignFirstResponderRec:(UIView*) view {
    if ([view respondsToSelector:@selector(resignFirstResponder)]){
        [view resignFirstResponder];
    }
    for (UIView * subview in [view subviews]){
        [self globalResignFirstResponderRec:subview];
    }
}



//set title with type
-(void)setTitleWithType
{
    if ([type isEqualToString:@"1"])
    {
        lbTitle.text = @"ติดตามงาน ที่ยังไม่ดำเนินการ";
    }
    if ([type isEqualToString:@"2"])
    {
        lbTitle.text = @"ติดตามงาน ที่อยู่ระหว่างดำเนินการ";
    }
    if ([type isEqualToString:@"3"])
    {
        lbTitle.text = @"ติดตามงาน ที่ดำเนินการเรียบร้อย";
    }
}



int rowNumberType3 = 20;
//set pull to refresh for completed task
-(void)setInfiniteScrollingForType3TaskCompleted
{
    [tblTaskList  addInfiniteScrollingWithActionHandler:^{
        
        int64_t delayInSeconds = 1;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            //[tblTaskList beginUpdates];

            
            rowNumberType3 = rowNumberType3+20;            
            NSString * strRowNumber = [NSString stringWithFormat:@"%d",rowNumberType3];
            
            
//            NSString *jsonURL=[NSString stringWithFormat:@"http://%@ListAllTaskType3CompletedWithHowManyTopRow.ashx?typeID=0&howManyRow=%@",serviceUrl,strRowNumber];
//            NSData *json = [NSData dataWithContentsOfURL:[NSURL URLWithString:jsonURL]];
            
            
            /////////////////new
            EGAUtility * Util = [[EGAUtility alloc]init];
            NSString *jsonURL=[NSString stringWithFormat:@"ListAllTaskType3CompletedWithHowManyTopRow.ashx&typeID=0&howManyRow=%@",strRowNumber];
            NSData *json =[Util getDataFromService:jsonURL];
            /////////////////new
            
            arrTask = [[NSMutableArray alloc]initWithArray:[NSJSONSerialization JSONObjectWithData:json options:kNilOptions error:nil]];

            
            //[tblTaskList endUpdates];
            [tblTaskList reloadData];
            [tblTaskList.infiniteScrollingView stopAnimating];
        });
    }];
}





-(void)addPullToRefreshToTable
{
    [tblTaskList addPullToRefreshWithActionHandler:^{
        
        int64_t delayInSeconds = 2.0;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [self refresh];
            [tblTaskList.pullToRefreshView stopAnimating];
        });
    }];

}


-(void)refresh
{
    ARC_DB * DB = [[ARC_DB alloc]init];
    if([DB internetConnected])
    {
        [DB saveAllTask];
        [self queryAndSetArr];
        [tblTaskList reloadData];
    }
    else
    {
        [self alertNotConnect];
    }
}



-(void)queryAndSetArr
{
    ARC_DB * DB = [[ARC_DB alloc]init];
    
    //set type here
    //NSString * type = @"0";
    
    if ([type isEqualToString:@"0"])
        arrTask = [DB getAllTaskType0];
    
    else if ([type isEqualToString:@"1"])
        arrTask = [DB getAllTaskType1];
    
    else if ([type isEqualToString:@"2"])
        arrTask = [DB getAllTaskType2];
    
    else if ([type isEqualToString:@"3"])
        arrTask = [DB getAllTaskType3];
}



//- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
//{
//    return [arrTask count];
//}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
{
        if(isFiltered)
    {
        return [filteredArrListNewBook count];
    }
    else
    {
        return [arrTask count];

    }
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
{
    // นำ dic ใน array ในแต่ละ row มาโชว์ใน tableview
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
    //if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle : UITableViewCellStyleSubtitle
                                      reuseIdentifier : @"Cell"];
    //}
    NSDictionary*dicForEachRow = [arrTask objectAtIndex:indexPath.row];
    
    
    ///////new
    
    if(isFiltered)
    {
        dicForEachRow = [filteredArrListNewBook objectAtIndex:indexPath.row];
    }
    else
    {
        dicForEachRow = [arrTask objectAtIndex:indexPath.row];
    }

    ///////new
    
    
    
    
    
    
    
    
    
    
    UILabel *l1=[[UILabel alloc]initWithFrame:CGRectMake(47, 0, 490,60)];
    l1.font = [UIFont systemFontOfSize:20];
    [l1 setTextColor:[UIColor darkGrayColor]];
    l1.text = [NSString stringWithFormat:@"  %@", [dicForEachRow objectForKey:@"Doc_Subject"]];
    [cell.contentView addSubview:l1];
    
    
    
    
    
    
    //CommandDate
    NSString * CommandDate = [dicForEachRow objectForKey:@"CommandDate"];
    EGAUtility * Util = [[EGAUtility alloc]init];
    NSString * CommandDateTH = [Util getDateTh:(CommandDate)];
    
    UILabel *lbCommandDateTH=[[UILabel alloc]initWithFrame:CGRectMake(550,9, 120,41)];
    [lbCommandDateTH setTextColor:[UIColor darkGrayColor]];
    lbCommandDateTH.textAlignment = NSTextAlignmentCenter;
    lbCommandDateTH.font = [UIFont systemFontOfSize:17];
    lbCommandDateTH.text = CommandDateTH;
    [cell.contentView addSubview:lbCommandDateTH];
    
    
    
    
    

    
    if ([[dicForEachRow objectForKey:@"TaskStatus"] isEqualToString:@"1"])
    {
        UIImageView * ivPriority = [[UIImageView alloc]initWithFrame:CGRectMake(665, 0, 60,60)];
        UIImage *img = [UIImage imageNamed:@"flag_yellow.png"];
        [ivPriority setImage:img];
        [cell.contentView addSubview:ivPriority];
    }
    if ([[dicForEachRow objectForKey:@"TaskStatus"] isEqualToString:@"2"])
    {
        UIImageView * ivPriority = [[UIImageView alloc]initWithFrame:CGRectMake(665, 0, 60,60)];
        UIImage *img = [UIImage imageNamed:@"flag_red.png"];
        [ivPriority setImage:img];
        [cell.contentView addSubview:ivPriority];
    }
    if ([[dicForEachRow objectForKey:@"TaskStatus"] isEqualToString:@"3"])
    {
        UIImageView * ivPriority = [[UIImageView alloc]initWithFrame:CGRectMake(665, 0, 60,60)];
        UIImage *img = [UIImage imageNamed:@"flag_red.png"];
        [ivPriority setImage:img];
        [cell.contentView addSubview:ivPriority];
    }
    if ([[dicForEachRow objectForKey:@"TaskStatus"] isEqualToString:@"4"])
    {
        UIImageView * ivPriority = [[UIImageView alloc]initWithFrame:CGRectMake(665, 0, 60,60)];
        UIImage *img = [UIImage imageNamed:@"flag_red.png"];
        [ivPriority setImage:img];
        [cell.contentView addSubview:ivPriority];
    }
    

    
    
    
    



    
    
    

    
    //set letter_open or letter_close image
    UIImageView *imgLetter=[[UIImageView alloc]initWithFrame:CGRectMake(0,0,41,41)];
    
    ARC_DB * db = [[ARC_DB alloc]init];
    
    BOOL isTaskOpened = [db isHasTaskDetailInDB:[dicForEachRow objectForKey:@"ID"] ];
    
    if ( isTaskOpened == YES )
    {
        imgLetter.image=[UIImage imageNamed:@"letter_open.png"];
    }
    else if ( isTaskOpened == NO )
    {
        imgLetter.image=[UIImage imageNamed:@"letter_close.png"];
    }
    
    cell.imageView.image = imgLetter.image;
    
    
    

    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    self.TLDA = [[taskListDetailAdmin alloc] initWithNibName:@"taskListDetailAdmin" bundle:nil];
    
    //set empid
    self.TLDA.EmpID = self.appDelegate.employeeInfo.EmpID;
    NSDictionary*dicForEachRow = [arrTask objectAtIndex:indexPath.row];
    
    //////new
    if(isFiltered)
    {
        dicForEachRow = [filteredArrListNewBook objectAtIndex:indexPath.row];
    }
    else
    {
        dicForEachRow = [arrTask objectAtIndex:indexPath.row];
    }

    //////new
    
    
    NSString * strDocID = [dicForEachRow objectForKey:@"ID"];
    self.TLDA.DocID = strDocID;
    [self.view addSubview:self.TLDA.view];
}


-(EGAAppDelegate*)appDelegate
{
    return  (EGAAppDelegate*)[[UIApplication sharedApplication] delegate];
}





-(void)alertNotConnect
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"ไม่สามารถเชื่อมต่อกับเซิฟเวอร์"
                                                    message:@"ทำให้ไม่สามารถอัพเดทข้อมูล"
                                                   delegate:nil
                                          cancelButtonTitle:@"OK"
                                          otherButtonTitles:nil];
    [alert show];
}












- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {
    
    [super dealloc];
}



-(void)searchBar:(UISearchBar*)searchBar textDidChange:(NSString*)text
{
    if(text.length == 0)
    {
        isFiltered = FALSE;
    }
    else
    {
        isFiltered = TRUE;
        filteredArrListNewBook = [[NSMutableArray alloc] init];
        
        for (NSDictionary*dicForEachRow in arrTask)
        {
          //  NSRange rangeFrom = [[dicForEachRow objectForKey:@"Org_Name"] rangeOfString:text options:NSCaseInsensitiveSearch];
            NSRange rangeName = [[dicForEachRow objectForKey:@"Doc_Subject"] rangeOfString:text options:NSCaseInsensitiveSearch];
          //  if(rangeName.location != NSNotFound || rangeFrom.location != NSNotFound)
            if(rangeName.location != NSNotFound)
            {
                [filteredArrListNewBook addObject:dicForEachRow];
            }
        }
    }
    
    [tblTaskList reloadData];
}
@end
